<?php
/*
 * @Author: zwx
 * @Date: 2024-08-18 16:40:12
 * @LastEditors: zwx
 * @LastEditTime: 2024-10-13 16:54:12
 * @Description: 从聚水潭拉取公域订单
 */

namespace app\apiadmin\controller\gongyu;

use app\apiadmin\controller\liveManager\LiveStatus;
use app\common\controller\BaseController;
use app\common\utils\Curl;
use think\facade\Db;
class GetOrdersFromJST extends BaseController
{

    // private $app_key = env('JST.app_key');
    // private $app_secret = env('JST.app_secret');


    public function __construct()
    {

    }

    /**
     * 聚水潭的Access_Token
     * @param $keys  存储token的字段名
     * @param $appid 程序appid
     * @param $appsecret   程序的密钥
     */
    public function getJuShuiTanAccessToken()
    {
        //检测本地是否已经拥有access_token，并且检测access_token是否过期
        $accessToken = $this->_checkJuShuiTanAccessToken();
        if ($accessToken === false) {
            // $accessToken = $this->_getJuShuiTanAccessToken();
            return $accessToken['access_token'];
        } else {
            return $accessToken['access_token'];
        }
    }


    /**
     * 聚水潭
     * 
     * 聚水潭的accesstoken  
     * @param $keys  存储token的字段名
     * @param $appid 程序appid
     * @param $appsecret   程序的密钥
     * @return error|string
     */
    private function _getJuShuiTanAccessToken()
    {
        // $app_key = "a4a15e3640e24d8aaf60b07452d6c443";
        //app_secret  287fe57a787d4098a7e9ca146b5fe3d7
        $app_key = env('JST.app_key');
        $app_secret = env('JST.app_secret');

        $common = Db::connect('mysql2')->table('un_common')->where(array('keys' => 'jushuitan_token'))->field('values')->find();
        $token = unserialize($common['values']);
        $queryUrl = 'https://openapi.jushuitan.com/openWeb/auth/refreshToken';  //令牌
        $data = array();

        $data['timestamp'] = time();
        $data['grant_type'] = "refresh_token";
        $data['charset'] = "utf-8";
        $data['scope'] = 'all';
        $data['refresh_token'] = $token['refresh_token'];
        $data['app_key'] = $app_key;
        $data['sign'] = $this->get_jushuitan_sign($data);

        $result = Curl::callWebServer($queryUrl, $data, 'POST', true, true);
        // dump($result);
        // dump(111);
        if (!empty($result) && $result['code'] == 0) {
            $accessToken['access_token'] = $result['data']['access_token'];
            $accessToken['refresh_token'] = $result['data']['refresh_token'];
            $accessToken['expires_in'] = $result['data']['expires_in'];
        } else {
            return $result;  //出错啦
        }

        //我们把token保存在数据库中
        $accessToken['time'] = time();
        Db::connect('mysql2')->table('un_common')->add(array('keys' => 'jushuitan_token', 'values' => serialize($accessToken)), array(), true);
        return $result;
    }

    /**
     * 聚水潭的ACCESS_TOKEN是否过期
     * access_token的有效期目前为2小时(7200秒)，需定时刷新。
     *  @param $keys  存储token的字段名
     * @return bool
     */
    private function _checkJuShuiTanAccessToken()
    {
        $data = Db::connect('mysql2')->table('un_common')->where(array('keys' => 'jushuitan_token'))->find();
        if ($data) {
            $data = unserialize($data['values']);
            if ($data && time() - $data['time'] < 15 * 24 * 60 * 60) {
                return $data;
            }
        }
        return false;
    }

    /**
     * 聚水潭数字签名规则
     * @param string $app_secret
     * @param Array $data  数组
     */
    public function get_jushuitan_sign($data)
    {
        // $app_secret = "287fe57a787d4098a7e9ca146b5fe3d7";
        $app_key = env('JST.app_key');
        $app_secret = env('JST.app_secret');
        if ($data == null) {
            return null;
        }
        ksort($data);
        $result_str = "";
        foreach ($data as $key => $val) {
            if ($key != null && $key != "" && $key != "sign") {
                $result_str = $result_str . $key . $val;
            }
        }
        $result_str = $app_secret . $result_str;
        // dump($result_str);
        $ret = bin2hex(md5($result_str, true));

        return $ret;
    }


    /************************************************       拉正常单            ******************************************** */

    /**
     * @author: zwx
     * @Description: 定时任务拉取订单
     * @Date: 2024-08-21 17:03:01
     */
    public function get_JST_ALL_Order()
    {
        // $start_time = '2024-08-22 00:00:00';
        $start_time = date("Y-m-d H:i:s", strtotime("-3 minute"));
        $end_time = date("Y-m-d H:i:s", time());
        //拉取正常单
        $this->getjushutanOrder('', $start_time, $end_time);

        //拉取售后单
        $this->getjushuitancancelOrder($start_time, $end_time);
    }

    /**
     * 拉取聚水潭订单（抖音、小红书、快手、视频号）
     */
    public function getjushutanOrder($order_nums = '', $start_time = '', $end_time = '', $page = 1, $ts = 1)
    {
        header("Content-type: text/html; charset=utf-8");
        try {
            $app_key = env('JST.app_key');
            $app_secret = env('JST.app_secret');
            // 获取token
            $accessToken = $this->getJuShuiTanAccessToken();

            $queryUrl = 'https://openapi.jushuitan.com/open/orders/single/query';
            $data = array();
            //公共参数
            $timestamp = time();
            $data['app_key'] = $app_key;
            $data['access_token'] = $accessToken;
            $data['timestamp'] = $timestamp;
            $data['charset'] = "utf-8";
            $data['version'] = 2;


            //业务参数
            if (empty($start_time)) {
                $start_time = date("Y-m-d H:i:s", strtotime("-1 minute"));
                $end_time = date("Y-m-d H:i:s", time());
            }
            $map = array();
            $map['page_index'] = $page;  //加载第几页 
            $map['page_size'] = 50;  //每页最多50条
            if ($order_nums != '') {
                $map['so_ids'] = [$order_nums];  //店铺编号  抖店
            } else {
                // $map['modified_begin'] = $start_time;   //起始时间，和结束时间必须同时存在，时间间隔不能超过七天，与线上单号不能同时为空
                // $map['modified_end'] = $end_time;      //结束时间，和起始时间必须同时存在，时间间隔不能超过七天，与线上单号不能同时为空
                $map['so_ids'] = ['6933575584889115699', 'P740018064077426181', '2335900017247356', '3715625608019838464'];  //店铺编号  抖店 
            }

            $map['date_type'] = 2;   //(0:修改时间modified，2:订单日期order_date，3:发货时间send_date；非必填，默认0)
            // $map['status'] = "WaitConfirm";    //订单状态：待付款：WaitPay；发货中：Delivering；被合并：Merged；异常：Question；被拆分：Split；等供销商|外仓发货：WaitOuterSent；已付款待审核：WaitConfirm；已客审待财审：WaitFConfirm；已发货：Sent；取消：Cancelled
            $map[] = ['start_ts', '>=', $ts]; //ts时间戳，sql server中的行版本号，该字段查询防止分页过程中漏单。查询条件值是大于等于的关系
            $map['is_get_total'] = true; //是否查询总条数默认true，如果使用start_ts查询，该值传false否则影响查询效率
            $data['biz'] = json_encode($map);
            $data['sign'] = $this->get_jushuitan_sign($data);

            $header = array("Content-Type:application/x-www-form-urlencoded;charset=UTF-8");

            $urlencoded = 'access_token=' . $accessToken . '&app_key=' . $app_key . '&biz=' . $data['biz'] . '&charset=utf-8&version=2&sign=' . $data['sign'] . '&timestamp=' . $timestamp;
            dump($data);
            $result = Curl::callWebServer($queryUrl, $urlencoded, 'POST', true, true, $header);
            dump($result);

            //写一份日志
            file_put_contents("./getjushuitanOrder.txt", date('Y-m-d H:i:s') . '---' . "getjushuitanOrder:" . json_encode($result) . "\n", FILE_APPEND);

            //压入redis缓存等待消费
            $liveStatus = new LiveStatus(0);
            $liveStatus->set_jst_order(json_encode($result));

            //存库一份
            $databackup = [];
            $databackup['params'] = json_encode($map);
            $databackup['result'] = json_encode($result);
            $databackup['type'] = 1;
            $databackup['flag'] = 1;
            $databackup['time'] = date('Y-m-d H:i:s');
            db::table('xh_jst_order_backup')->insertGetId($databackup);

            //计算ts值
            foreach ($result['data']['orders'] as $k => $v) {
                $ts = $v['ts'];
            }

            //下一页
            if ($result['data']['has_next']) {
                $this->getjushutanOrder('', $start_time, $end_time, $result['data']['page_index'] + 1, $ts);
            }

            return;

        } catch (\PDOException $e) {
            //写一份日志
            file_put_contents("./jushuitan_error.txt", date('Y-m-d H:i:s') . '---' . "getjushuitanOrder:" . json_encode($e->getMessage()) . "\n", FILE_APPEND);
            throw $e;
        }
    }


    /**
     * @author: zwx
     * @Description: 后台服务   消费拉单数据
     * @Date: 2024-08-20 10:15:31
     */
    public function xiaofei_JST_Order()
    {
        //压入redis缓存等待消费
        $liveStatus = new LiveStatus(0);

        while (true) {

            try {
                $orders = $liveStatus->get_jst_order();  //从redis中取数

                if (!empty($orders)) {
                    $this->_xiaofei_JST_Orders($orders[1]);  //消费聚水潭订单数据
                } else {
                    sleep(1);
                }
            } catch (\Throwable $th) {
                dump('报错了-----------------------------------------------------');
                dump($th);
                file_put_contents("./jushuitan_error.txt", date('Y-m-d H:i:s') . '---' . "xiaofei_JST_Order:" . json_encode($th) . "\n", FILE_APPEND);
            }

        }

    }


    /**
     * @author: zwx
     * @Description: 消费聚水潭数据订单
     * @param {*} $orders
     * @Date: 2024-08-18 18:41:02
     */
    public function _xiaofei_JST_Orders($orders)
    {
        header("Content-type: text/html; charset=utf-8");
        try {

            //转换为数组
            $result = json_decode($orders, true);

            //报错返回
            if ($result['code'] != 0) {
                file_put_contents("./jushuitan_error.txt", date('Y-m-d H:i:s', time()) . '---_xiaofei_JSTOrders----请求返回错误----' . json_encode($result) . "\n", FILE_APPEND);
                dump('错误' . json_encode($result));
                return;
            }

            //没有订单返回
            if (!$result['data']['orders']) {
                dump('没有订单');
                return;
            }

            $ids = array();  //返回数据的订单号数组

            foreach ($result['data']['orders'] as $k => $v) {

                //查询店铺信息
                $where = array();
                $where['del'] = 0;
                $where['shop_id'] = $v['shop_id'];
                $shop = db::table('xh_jst_shop')->where($where)->find();
                if (!$shop) {
                    file_put_contents("./jushuitan_error.txt", date('Y-m-d H:i:s', time()) . '---_xiaofei_JSTOrders----店铺信息不存在----' . json_encode($result) . "\n", FILE_APPEND);
                    dump('店铺信息不存在');
                    continue;
                }

                if ($v['status'] == 'Cancelled' && count($v['pays']) == 0) {   //只要  已付款待审核 和  已发货 和退款  的订单
                    continue;
                }

                foreach ($v['items'] as $k1 => $v1) {

                    $ordernum = $this->_getStringByPingtaiOrderNum($shop['pingtai_id'], $v1['outer_oi_id'], $v1['raw_so_id']);
                    $i_id = $this->_getStringByPingtaiGoods($shop['pingtai_id'], $v1['shop_i_id'], $v1['i_id']);

                    $ids[] = $ordernum;

                    $a = [];
                    $a['shop_id'] = $v['shop_id'];
                    $a['pingtai_id'] = $shop['pingtai_id'];
                    $a['order_num'] = $ordernum;
                    $a['i_id'] = $i_id;
                    $goodsids[] = $a;
                }
            }


            //与本地存储的数据进行比较排重，筛选出需要添加的订单
            $where = [];
            $where[] = ['order_num', 'in', $ids];
            $where[] = ['time', '>=', strtotime(date('Y-m-d', time()) . '-1 day')];
            $yiyou1 = db::table('xh_ordernum')->where($where)->field('order_num')->select()->toArray();

            if ($yiyou1) {
                $yiyou = array_column($yiyou1, 'order_num');
                $addids = array_diff($ids, $yiyou);
            } else {
                $addids = $ids;
            }
            // dump('addids---' . json_encode($addids));
            //如果订单重复，则不添加
            if (!$addids) {
                dump('重复订单，无需添加');
                return;
            }

            //过滤出商品ID信息
            // 使用array_filter和in_array筛选二维数组
            $addgoods = array_filter($goodsids, function ($item) use ($addids) {
                return in_array($item['order_num'], $addids);
            });

            // dump($addgoods);
            $i_ids = array_column($addgoods, 'i_id');
            //查询商品信息
            $where = [];
            $where[] = ['goodsid', 'in', $i_ids];
            $goods = db::table('xh_jst_shop_goods')->where($where)->select()->toArray();
            // dump(db::table('xh_jst_shop_goods')->where($where)->fetchSql()->select());

            foreach ($addgoods as $k => $v) {
                foreach ($goods as $k1 => $v1) {
                    if ($v['i_id'] == $v1['goodsid']) {
                        $addgoods[$k]['pingtai_id'] = $v1['pingtai_id'];
                        $addgoods[$k]['goods_id'] = $v1['goodsid'];
                    }
                }
            }
            dump($addgoods);
            //组合数据
            $orders = [];
            $ordernums = [];

            foreach ($result['data']['orders'] as $k => $v) {
                $type = 1;
                if ($v['status'] == 'Cancelled') {   //只要  已付款待审核 和  已发货   的订单
                    if (count($v['pays']) == 0) {   //只要  已付款待审核 和  已发货   的订单
                        continue;
                    }
                    $type = 2;

                }
                //查询店铺信息
                $where = array();
                $where['del'] = 0;
                $where['shop_id'] = $v['shop_id'];
                $shop = db::table('xh_jst_shop')->where($where)->find();
                foreach ($v['items'] as $k1 => $v1) {
                    foreach ($addgoods as $k2 => $v2) {
                        $ordernum = $this->_getStringByPingtaiOrdernum($shop['pingtai_id'], $v1['outer_oi_id'], $v1['raw_so_id']);
                        if ($ordernum == $v2['order_num']) {
                            //添到表
                            $c = $this->_addXXH($v, $v1, $v2, $type);
                            if (!$c) {
                                continue;
                            }
                            // dump($c);
                            $orders[] = $c['a'];
                            $ordernums[] = $c['b'];
                        }
                    }
                }
            }

            //插入数据表
            db::table('xh_order_1')->insertAll($orders);
            db::table('xh_ordernum')->insertAll($ordernums);

            //给订单打短码标签
            if ($orders) {

                foreach ($orders as $k => $v) {
                    $this->dabiaoqian($v);
                }

                //预分配
                $order_nums = array_column($orders, 'order_num');
                $this->xiaoxuehua_yufenpei($order_nums);
            }



            dump('插入成功---' . count($orders));
        } catch (\PDOException $e) {
            //写一份日志
            file_put_contents("./jushuitan_error.txt", date('Y-m-d H:i:s') . '---' . "_xiaofei_JST_Orders:" . json_encode($e->getMessage()) . "\n", FILE_APPEND);
            throw $e;
        }

    }


    /**
     * @author: zwx
     * @Description: 根据平台ID的不同返回对应的字段值
     * @param {*} $pigntai_id
     * @param {*} $shop_i_id
     * @param {*} $i_id
     * @Date: 2024-08-20 14:22:45
     */
    private function _getStringByPingtaiOrderNum($pigntai_id, $shop_i_id, $i_id)
    {

        if ($pigntai_id == 1) {  //抖音
            return $i_id;
        } else if ($pigntai_id == 2) {  // 小红书
            return $i_id;
        } else if ($pigntai_id == 4) {  // 快手
            return $i_id;
        } else if ($pigntai_id == 6) {  // 视频号
            return $i_id;
        }

    }

    /**
     * @author: zwx
     * @Description: 根据平台ID的不同返回对应的字段值
     * @param {*} $pigntai_id
     * @param {*} $shop_i_id
     * @param {*} $i_id
     * @Date: 2024-08-20 14:22:45
     */
    private function _getStringByPingtaiGoods($pigntai_id, $shop_i_id, $i_id)
    {

        if ($pigntai_id == 1) {  //抖音
            return $i_id;
        } else if ($pigntai_id == 2) {  // 小红书
            return $i_id;
        } else if ($pigntai_id == 4) {  // 快手
            return $i_id;
        } else if ($pigntai_id == 6) {  // 视频号
            return $shop_i_id;
        }

    }



    /**
     * @author: zwx
     * @Description: 将订单插入到数据表中
     * @param {*} $result
     * @param {*} $addgoods  订单和商品信息  order_num  i_id  shop_id
     * @Date: 2024-08-20 13:52:53
     */
    private function _addXXH($order, $result, $addgoods, $type)
    {
        dump($addgoods);
        try {
            //查询店铺信息
            $where = array();
            $where['del'] = 0;
            $where['shopid'] = $addgoods['shop_id'];
            $where['goodsid'] = $addgoods['i_id'];
            $goods = db::table('xh_jst_shop_goods')->where($where)->find();
            if (!$goods) {
                dump($order);
                file_put_contents("./jushuitan_error.txt", date('Y-m-d H:i:s', time()) . '---_addXXH----商品信息不存在----' . json_encode($where) . "\n", FILE_APPEND);
                dump('商品信息不存在');
                return false;
            }

            $a = array();
            $a['courseid'] = $goods['courseid'];
            $a['out_order_no'] = $result['raw_so_id'];
            $a['order_num'] = $result['raw_so_id'];
            $a['order_nums'] = $result['raw_so_id'];
            $a['total_fee'] = $result['amount'] * 100;
            $a['pingtai'] = $addgoods['pingtai_id'];
            $a['i_id'] = $addgoods['i_id'];
            // $a['laiyuan'] = $laiyuan['id'];
            $a['app_id'] = $addgoods['shop_id'];
            $a['time'] = $order['created'];
            $a['del'] = 0;
            $a['tel'] = '';


            $a['order_status'] = $type;
            dump($order);
            if ($order['pays'][0]['payment'] == '微信') {
                $a['pay_method'] = 1;
            } else if ($order['pays'][0]['payment'] == '支付宝') {
                $a['pay_method'] = 2;
            } else {
                $a['pay_method'] = 6;
            }
            $a['pay_state'] = 1;
            $a['pay_time'] = $order['pay_date'];

            $a['jinrufangshi'] = '';

            //达人信息
            $a['referrer_id'] = isset($order['referrer_id']) ? $order['referrer_id'] : '';
            $a['referrer_name'] = isset($order['referrer_name']) ? $order['referrer_name'] : '';


            //存储id临时表
            $b = array();
            $b['courseid'] = $a['courseid'];
            $b['order_num'] = $a['order_num'];
            $b['out_order_no'] = $a['out_order_no'];
            $b['state'] = $type;
            $b['tel'] = $a['tel'];
            $b['time'] = $a['time'];
            $b['app_id'] = $addgoods['shop_id'];
            $b['qiyeid'] = 1;
            $b['pingtai'] = $addgoods['pingtai_id']; //1:抖音
            // $b['laiyuan'] = $laiyuan['id'];

            return ['a' => $a, 'b' => $b];
        } catch (\PDOException $e) {
            //写一份日志
            file_put_contents("./jushuitan_error.txt", date('Y-m-d H:i:s') . '---' . "_addXXH:" . json_encode($e->getMessage()) . "\n", FILE_APPEND);
            throw $e;
        }
    }

    /***************************************     拉退单                     *********************************************** */

    /**
     * 拉取聚水潭售后订单数据
     */
    public function getjushuitancancelOrder($start_time = '', $end_time = '', $page = 1, $ts = 1)
    {
        header("Content-type: text/html; charset=utf-8");
        sleep(2);
        try {
            $app_key = env('JST.app_key');
            $app_secret = env('JST.app_secret');
            // 获取token
            $accessToken = $this->getJuShuiTanAccessToken();

            $queryUrl = 'https://openapi.jushuitan.com/open/refund/single/query';
            $data = array();
            //公共参数
            $app_key = $app_key;
            $timestamp = time();
            $data['app_key'] = $app_key;
            $data['access_token'] = $accessToken;
            $data['timestamp'] = $timestamp;
            $data['charset'] = "utf-8";
            $data['version'] = 2;

            //业务参数
            if (empty($start_time)) {
                $start_time = date("Y-m-d H:i:s", strtotime("-1 minute"));
                $end_time = date("Y-m-d H:i:s", time());
            }

            $map = array();
            $map['page_index'] = $page;  //加载第几页 
            $map['page_size'] = 50;  //每页最多50条
            $map['so_ids'] = ['6933519966624749442', 'P739862795679177181', '2335900015503286', '3715602175142790656'];  //店铺编号  抖店 
            // $map['modified_begin'] = $start_time;   //起始时间，和结束时间必须同时存在，时间间隔不能超过七天，与线上单号不能同时为空
            // $map['modified_end'] = $end_time;      //结束时间，和起始时间必须同时存在，时间间隔不能超过七天，与线上单号不能同时为空
            $map['date_type'] = 2;   //(0:修改时间modified，2:订单日期order_date，3:发货时间send_date；非必填，默认0)
            // $map['status'] = "Cancelled";    //售后单状态（WaitConfirm:待确认,Confirmed:已确认,Cancelled:作废,Merged:被合并）
            $map[] = ['start_ts', '>=', $ts]; //ts时间戳，sql server中的行版本号，该字段查询防止分页过程中漏单。查询条件值是大于等于的关系
            $map['is_get_total'] = true; //是否查询总条数默认true，如果使用start_ts查询，该值传false否则影响查询效率
            $data['biz'] = json_encode($map);
            $data['sign'] = $this->get_jushuitan_sign($data);

            $header = array("Content-Type:application/x-www-form-urlencoded;charset=UTF-8");

            $urlencoded = 'access_token=' . $accessToken . '&app_key=' . $app_key . '&biz=' . $data['biz'] . '&charset=utf-8&version=2&sign=' . $data['sign'] . '&timestamp=' . $timestamp;

            $result = Curl::callWebServer($queryUrl, $urlencoded, 'POST', true, true, $header);
            dump($result);
            // die;
            //写一份日志
            file_put_contents("./getjushuitanOrder_cancel.txt", date('Y-m-d H:i:s') . '---' . "cancelOrder_doudian_all:" . json_encode($result) . "\n", FILE_APPEND);

            //压入redis缓存等待消费
            $liveStatus = new LiveStatus(0);
            $liveStatus->set_jst_cancel_order(json_encode($result));

            //存库一份
            $databackup = [];
            $databackup['params'] = json_encode($map);
            $databackup['result'] = json_encode($result);
            $databackup['type'] = 2;
            $databackup['time'] = date('Y-m-d H:i:s');
            db::table('xh_jst_order_backup')->insertGetId($databackup);

            //计算ts值
            foreach ($result['data']['datas'] as $k => $v) {
                $ts = $v['ts'];
            }

            //下一页
            if ($result['data']['has_next']) {
                $this->getjushuitancancelOrder($start_time, $end_time, $result['data']['page_index'] + 1, $ts);
            }
        } catch (\PDOException $e) {
            //写一份日志
            file_put_contents("./jushuitan_error.txt", date('Y-m-d H:i:s') . '---' . "getjushuitancancelOrder:" . json_encode($e->getMessage()) . "\n", FILE_APPEND);
            throw $e;
        }
    }


    /**
     * @author: zwx
     * @Description: 后台服务   消费退款的订单数据
     * @Date: 2024-08-20 10:15:31
     */
    public function xiaofei_JST_Cancel_Order()
    {
        //压入redis缓存等待消费
        $liveStatus = new LiveStatus(0);

        while (true) {

            try {
                $orders = $liveStatus->get_jst_cancel_order();  //从redis中取数

                if (!empty($orders)) {
                    $this->_xiaofei_JST_cancel_Orders($orders[1]);  //消费聚水潭订单数据
                } else {
                    sleep(1);
                }
            } catch (\Throwable $th) {
                dump('报错了-----------------------------------------------------');
                dump($th);
                file_put_contents("./jushuitan_error.txt", date('Y-m-d H:i:s') . '---' . "getJSTOrder:" . json_encode($th));
            }

        }

    }


    /**
     * @author: zwx
     * @Description: 消费售后单数据
     * @param {*} $orders
     * @Date: 2024-08-21 10:55:13
     */
    private function _xiaofei_JST_cancel_Orders($orders)
    {
        try {
            $result = json_decode($orders, true); //获取聚水潭订单数据

            //报错返回
            if ($result['code'] != 0) {
                file_put_contents("./jushuitan_error.txt", date('Y-m-d H:i:s', time()) . '---_xiaofei_JST_cancel_Orders----请求返回错误----' . json_encode($result) . "\n", FILE_APPEND);
                dump('错误' . json_encode($result));
                return;
            }

            //没有订单返回
            if (!$result['data']['datas']) {
                dump('没有订单');
                return;
            }

            //订单数组
            $ids = array();  //抖店订单的订单号数组
            foreach ($result['data']['datas'] as $k => $v) {
                if ($v['shop_status'] == 'SUCCESS') {  //退款成功
                    //查询店铺信息
                    $where = array();
                    $where['del'] = 0;
                    $where['shop_id'] = $v['shop_id'];
                    $shop = db::table('xh_jst_shop')->where($where)->find();
                    foreach ($v['items'] as $k1 => $v1) {
                        $ordernum = explode(':', $v1['raw_so_id'])[1];
                        $ids[] = $ordernum;
                    }
                }
            }

            //与本地存储的数据进行比较排重，筛选出需要添加的订单
            if ($ids) {
                $where = [];
                $where['del'] = 0;
                $where[] = ['order_num', 'in', $ids];

                $addids1 = db::table('xh_order_1')->where($where)->field('order_num')->select()->toArray();
                if ($addids1) {
                    $addids2 = array_column($addids1, 'order_num');
                    $addids = array_diff($ids, $addids2);
                } else {
                    $addids = $ids;
                }
            } else {
                $addids = '';
            }

            if (!$addids) {
                dump('重复订单，无需添加');
                return;
            }

            //组装订单数据
            foreach ($result['data']['datas'] as $k => $v) {
                foreach ($v['items'] as $k1 => $v1) {
                    $ordernum = explode(':', $v1['raw_so_id'])[1];
                    foreach ($addids as $k2 => $v2) {
                        if ($ordernum == $v2) {
                            $this->_delXXHOrder($v2, $v['refund'], $v['as_date'], $v['modified']);

                        }
                    }
                }
            }
        } catch (\PDOException $e) {
            //写一份日志
            file_put_contents("./jushuitan_error.txt", date('Y-m-d H:i:s') . '---' . "_xiaofei_JST_cancel_Orders:" . json_encode($e->getMessage()) . "\n", FILE_APPEND);
            throw $e;
        }
    }

    /**
     * @author: zwx
     * @Description: 删除小雪花订单以及添加订单表
     * @param {*} $order_num
     * @param {*} $refund_fee
     * @param {*} $refund_time
     * @Date: 2024-03-14 20:23:34
     */
    private function _delXXHOrder($order_num, $refund_fee, $as_date, $refund_time)
    {
        try {

            $order = db::table('xh_order_1')->where(array('order_num' => $order_num))->find();

            if ($order) {
                $data = array();
                $data['refund_fee'] = $refund_fee * 100;
                $data['refund_time'] = date('Y-m-d H:i:s', $refund_time);
                $data['order_status'] = 3;

                db::table('xh_order_1')->where(array('order_num' => $order_num))->save($data);

                $data = array();
                $data['state'] = 3;
                $data['out_refund_no'] = 'T' . $order['order_num'];
                $data['refund_time'] = date('Y-m-d H:i:s', $refund_time);
                db::table('xh_ordernum')->where(array('order_num' => $order_num))->save($data);

            } else {
                //插入订单数据
                $this->getjushutanOrder($order_num, '2024-01-01', '2024-01-01', 1, 1);
            }

            //添加退款单
            $data = array();
            $data['refund_id'] = '';
            $data['order_num'] = $order_num;
            $data['out_refund_no'] = 'T' . $order_num;
            $data['out_order_no'] = $order_num;
            $data['apply_time'] = $as_date;
            $data['state'] = 3;
            $data['refund_time'] = $refund_time;
            $data['app_id'] = '';
            $data['fee'] = $refund_fee * 100;
            $data['operation_time'] = date('Y-m-d H:i:s', time());
            // $data['remark'] = '['.implode(',',$msg->refund_reason).']-'.$msg->refund_description;
            $refund = db::table('xh_refundorder_1')->where(array('order_num' => $order_num))->select();
            if (count($refund) == 0) {
                db::table('xh_refundorder_1')->insertGetId($data);
            }

        } catch (\PDOException $e) {
            //写一份日志
            file_put_contents("./jushuitan_error.txt", date('Y-m-d H:i:s') . '---' . "_delXXHOrder:" . json_encode($e->getMessage()) . "\n", FILE_APPEND);
            throw $e;
        }

    }


    /************************************          补漏拉单                   ************************************* */

    // 获取订单  查漏补缺 2024年8月21日16:02:42
    public function get_JST_OrderALL_BuLou()
    {

        $start_time = date('Y-m-d', strtotime('-1 day'));
        $end_time = date('Y-m-d');

        //拉取正常单
        $this->getjushutanOrder_BuLou('', $start_time, $end_time);

        //拉取售后单
        $this->getjushuitancancelOrder_BuLou($start_time, $end_time);

    }


    /**
     * 拉取聚水潭订单（抖音、小红书、快手、视频号）
     */
    public function getjushutanOrder_BuLou($order_nums = '', $start_time = '', $end_time = '', $page = 1, $ts = 1)
    {
        header("Content-type: text/html; charset=utf-8");
        try {
            $app_key = env('JST.app_key');
            $app_secret = env('JST.app_secret');
            // 获取token
            $accessToken = $this->getJuShuiTanAccessToken();

            $queryUrl = 'https://openapi.jushuitan.com/open/orders/single/query';
            $data = array();
            //公共参数
            $timestamp = time();
            $data['app_key'] = $app_key;
            $data['access_token'] = $accessToken;
            $data['timestamp'] = $timestamp;
            $data['charset'] = "utf-8";
            $data['version'] = 2;


            //业务参数
            if (empty($start_time)) {
                $start_time = date("Y-m-d H:i:s", strtotime("-1 minute"));
                $end_time = date("Y-m-d H:i:s", time());
            }
            $map = array();
            $map['page_index'] = $page;  //加载第几页 
            $map['page_size'] = 50;  //每页最多50条
            if ($order_nums != '') {
                $map['so_ids'] = [$order_nums];  //店铺编号  抖店
            } else {
                $map['modified_begin'] = $start_time;   //起始时间，和结束时间必须同时存在，时间间隔不能超过七天，与线上单号不能同时为空
                $map['modified_end'] = $end_time;      //结束时间，和起始时间必须同时存在，时间间隔不能超过七天，与线上单号不能同时为空
                // $map['so_ids'] = ['6933575584889115699', 'P740018064077426181', '2335900017247356', '3715625608019838464'];  //店铺编号  抖店 
            }

            $map['date_type'] = 2;   //(0:修改时间modified，2:订单日期order_date，3:发货时间send_date；非必填，默认0)
            // $map['status'] = "WaitConfirm";    //订单状态：待付款：WaitPay；发货中：Delivering；被合并：Merged；异常：Question；被拆分：Split；等供销商|外仓发货：WaitOuterSent；已付款待审核：WaitConfirm；已客审待财审：WaitFConfirm；已发货：Sent；取消：Cancelled
            $map[] = ['start_ts', '>=', $ts]; //ts时间戳，sql server中的行版本号，该字段查询防止分页过程中漏单。查询条件值是大于等于的关系
            $map['is_get_total'] = true; //是否查询总条数默认true，如果使用start_ts查询，该值传false否则影响查询效率
            $data['biz'] = json_encode($map);
            $data['sign'] = $this->get_jushuitan_sign($data);

            $header = array("Content-Type:application/x-www-form-urlencoded;charset=UTF-8");

            $urlencoded = 'access_token=' . $accessToken . '&app_key=' . $app_key . '&biz=' . $data['biz'] . '&charset=utf-8&version=2&sign=' . $data['sign'] . '&timestamp=' . $timestamp;
            dump($data);
            $result = Curl::callWebServer($queryUrl, $urlencoded, 'POST', true, true, $header);
            dump($result);

            //写一份日志
            file_put_contents("./getjushuitanOrder.txt", date('Y-m-d H:i:s') . '---' . "getjushuitanOrder_bulou:" . json_encode($result) . "\n", FILE_APPEND);

            //压入redis缓存等待消费
            $liveStatus = new LiveStatus(0);
            $liveStatus->set_jst_order_bulou(json_encode($result));

            //存库一份
            $databackup = [];
            $databackup['params'] = json_encode($map);
            $databackup['result'] = json_encode($result);
            $databackup['type'] = 3;
            $databackup['time'] = date('Y-m-d H:i:s');
            db::table('xh_jst_order_backup')->insertGetId($databackup);

            //计算ts值
            foreach ($result['data']['orders'] as $k => $v) {
                $ts = $v['ts'];
            }

            //下一页
            if ($result['data']['has_next']) {
                $this->getjushutanOrder_buLou('', $start_time, $end_time, $result['data']['page_index'] + 1, $ts);
            }

            return;

        } catch (\PDOException $e) {
            //写一份日志
            file_put_contents("./jushuitan_error.txt", date('Y-m-d H:i:s') . '---' . "getjushuitanOrder_bulou:" . json_encode($e->getMessage()) . "\n", FILE_APPEND);
            throw $e;
        }
    }


    /**
     * @author: zwx
     * @Description: 后台服务   消费拉单数据
     * @Date: 2024-08-20 10:15:31
     */
    public function xiaofei_JST_Order_BuLou()
    {
        //压入redis缓存等待消费
        $liveStatus = new LiveStatus(0);

        while (true) {

            try {
                $orders = $liveStatus->get_jst_order_bulou();  //从redis中取数

                if (!empty($orders)) {
                    $this->_xiaofei_JST_Orders($orders[1]);  //消费聚水潭订单数据
                } else {
                    sleep(1);
                }
            } catch (\Throwable $th) {
                dump('报错了-----------------------------------------------------');
                dump($th);
                file_put_contents("./jushuitan_error.txt", date('Y-m-d H:i:s') . '---' . "xiaofei_JST_Order_bulou:" . json_encode($th) . "\n", FILE_APPEND);
            }

        }

    }


    /**
     * 拉取聚水潭售后订单数据
     */
    public function getjushuitancancelOrder_BuLou($start_time = '', $end_time = '', $page = 1, $ts = 1)
    {
        header("Content-type: text/html; charset=utf-8");
        sleep(2);
        try {
            $app_key = env('JST.app_key');
            $app_secret = env('JST.app_secret');

            // 获取token
            $accessToken = $this->getJuShuiTanAccessToken();

            $queryUrl = 'https://openapi.jushuitan.com/open/refund/single/query';
            $data = array();
            //公共参数

            $timestamp = time();
            $data['app_key'] = $app_key;
            $data['access_token'] = $accessToken;
            $data['timestamp'] = $timestamp;
            $data['charset'] = "utf-8";
            $data['version'] = 2;

            //业务参数
            if (empty($start_time)) {
                $start_time = date("Y-m-d H:i:s", strtotime("-1 minute"));
                $end_time = date("Y-m-d H:i:s", time());
            }

            $map = array();
            $map['page_index'] = $page;  //加载第几页 
            $map['page_size'] = 50;  //每页最多50条
            $map['so_ids'] = ['6933519966624749442', 'P739862795679177181', '2335900015503286', '3715602175142790656'];  //店铺编号  抖店 
            // $map['modified_begin'] = $start_time;   //起始时间，和结束时间必须同时存在，时间间隔不能超过七天，与线上单号不能同时为空
            // $map['modified_end'] = $end_time;      //结束时间，和起始时间必须同时存在，时间间隔不能超过七天，与线上单号不能同时为空
            $map['date_type'] = 2;   //(0:修改时间modified，2:订单日期order_date，3:发货时间send_date；非必填，默认0)
            // $map['status'] = "Cancelled";    //售后单状态（WaitConfirm:待确认,Confirmed:已确认,Cancelled:作废,Merged:被合并）
            $map[] = ['start_ts', '>=', $ts]; //ts时间戳，sql server中的行版本号，该字段查询防止分页过程中漏单。查询条件值是大于等于的关系
            $map['is_get_total'] = true; //是否查询总条数默认true，如果使用start_ts查询，该值传false否则影响查询效率
            $data['biz'] = json_encode($map);
            $data['sign'] = $this->get_jushuitan_sign($data);

            $header = array("Content-Type:application/x-www-form-urlencoded;charset=UTF-8");

            $urlencoded = 'access_token=' . $accessToken . '&app_key=' . $app_key . '&biz=' . $data['biz'] . '&charset=utf-8&version=2&sign=' . $data['sign'] . '&timestamp=' . $timestamp;

            $result = Curl::callWebServer($queryUrl, $urlencoded, 'POST', true, true, $header);
            dump($result);
            // die;
            //写一份日志
            file_put_contents("./getjushuitanOrder_cancel_bulou.txt", date('Y-m-d H:i:s') . '---' . "getjushuitancancelOrder_BuLou:" . json_encode($result) . "\n", FILE_APPEND);

            //压入redis缓存等待消费
            $liveStatus = new LiveStatus(0);
            $liveStatus->set_jst_cancel_order_bulou(json_encode($result));

            //存库一份
            $databackup = [];
            $databackup['params'] = json_encode($map);
            $databackup['result'] = json_encode($result);
            $databackup['type'] = 4;
            $databackup['time'] = date('Y-m-d H:i:s');
            db::table('xh_jst_order_backup')->insertGetId($databackup);

            //计算ts值
            foreach ($result['data']['datas'] as $k => $v) {
                $ts = $v['ts'];
            }

            //下一页
            if ($result['data']['has_next']) {
                $this->getjushuitancancelOrder_BuLou($start_time, $end_time, $result['data']['page_index'] + 1, $ts);
            }
        } catch (\PDOException $e) {
            //写一份日志
            file_put_contents("./jushuitan_error_bulou.txt", date('Y-m-d H:i:s') . '---' . "getjushuitancancelOrder_BuLou:" . json_encode($e->getMessage()) . "\n", FILE_APPEND);
            throw $e;
        }
    }


    /**
     * @author: zwx
     * @Description: 后台服务   消费退款的订单数据  补漏
     * @Date: 2024-08-20 10:15:31
     */
    public function xiaofei_JST_Cancel_Order_BuLou()
    {
        //压入redis缓存等待消费
        $liveStatus = new LiveStatus(0);

        while (true) {

            try {
                $orders = $liveStatus->get_jst_cancel_order_bulou();  //从redis中取数

                if (!empty($orders)) {
                    $this->_xiaofei_JST_cancel_Orders($orders[1]);  //消费聚水潭订单数据
                } else {
                    sleep(1);
                }
            } catch (\Throwable $th) {
                dump('报错了-----------------------------------------------------');
                dump($th);
                file_put_contents("./jushuitan_error_bulou.txt", date('Y-m-d H:i:s') . '---' . "xiaofei_JST_Cancel_Order_BuLou:" . json_encode($th) . "\n", FILE_APPEND);
            }

        }

    }


    /****************************************************            打标签               ****************************************************** */

    /**
     * 打标签
     */
    function dabiaoqian($data)
    {
        try {
            //压入redis缓存等待消费
            $liveStatus = new LiveStatus(0);
            $liveStatus->set_jst_dabiaoqain(json_encode($data['order_num']));  //从redis中取数
        } catch (\Throwable $th) {
            dump('报错了-----------------------------------------------------');
            dump($th);

            file_put_contents("./biaoqian_error.txt", date('Y-m-d H:i:s') . '---' . "dabiaoqian:" . json_encode($th) . "\n", FILE_APPEND);
        }
    }


    /**
     * @author: zwx
     * @Description: 消费标签
     * @Date: 2024-08-26 20:53:31
     */
    function xiaofei_biaoqian()
    {

        $liveStatus = new LiveStatus(0);
        while (true) {
            try {
                $_addExternalUser = $liveStatus->get_jst_dabiaoqain();
                if (!empty($_addExternalUser)) {
                    $this->_xiaofei_biaoqian($_addExternalUser[1]);
                } else {
                    sleep(1);
                }
            } catch (\Throwable $th) {
                dump('报错了-----------------------------------------------------');
                dump($th);

                file_put_contents("./biaoqian_error.txt", date('Y-m-d H:i:s') . '---' . "xiaofei_biaoqian:" . json_encode($th) . "\n", FILE_APPEND);
            }
        }



    }

    function _xiaofei_biaoqian($order_num)
    {

        $o = json_decode($order_num, true);
        dump($o);
        $a = $this->short_Code();
        $data2 = [];
        $data2['short_code'] = $a;
        $c = db::table('xh_order_1')->where(array('order_num' => $o))->save($data2);
        dump($o . '-------' . db::table('xh_order_1')->where(array('order_num' => $o))->fetchSql()->save($data2) . '----' . $c);
        file_put_contents("./biaoqian.txt", date('Y-m-d H:i:s') . '---' . "_xiaofei_biaoqian:" . json_encode($o) . '----' . json_encode($data2) . "\n", FILE_APPEND);
    }


    /**
     * @author: zwx
     * @Description: 给订单生成短编码  404180001
     * @return {*} $code  生成的编码  404180001
     * @Date: 2024-04-18 14:58:23
     */
    function short_Code()
    {

        $where = array();
        $where['del'] = 0;
        $where[] = ["time", '>', date('Y-m-d')];
        $where[] = ["time", '<=', date('Y-m-d', time() + 86400)];
        $where[] = ['short_code', 'exp', Db::raw('IS NOT NULL')];
        $num = db::table('xh_order_1')->where($where)->count(); //所有订单
        dump(db::table('xh_order_1')->where($where)->fetchSql()->count() . '----' . $num);
        $num++; //加一

        $num = str_pad($num, 5, "0", STR_PAD_LEFT); //不足补零

        $nian = date('y');
        $yue = date('m');
        $ri = date('d');

        $wan = substr($num, 0, 1);
        $qian = substr($num, 1, 1);
        $bai = substr($num, 2, 1);
        $shi = substr($num, 3, 1);
        $ge = substr($num, 4, 1);

        $code = $nian . $yue . $ri . $wan . $qian . $bai . $shi . $ge; //拼接   404180001

        return $code;

    }


    /**
     * 雪花预分配助教
     * 2024年4月17日 00:51:47
     * @param $orderlist 订单号列表
     * @author Sani
     */
    function xiaoxuehua_yufenpei($orderlist)
    {
        //写一段crul请求，参数传数组
        $url = "https://lyzxuehua.banxued.com/LooseCodeApi/batchAutoDistributionApi";
        $result['qiye_id'] = 1;
        $result['order_num'] = $orderlist;
        $output = Curl::callWebServer($url, json_encode($result), 'POST', true, true);

        file_put_contents("./yufenpei.txt", date('Y-m-d H:i:s') . '---' . "xiaoxuehua_yufenpei:" . json_encode($result) . '--result--' . json_encode($output) . "\n", FILE_APPEND);
    }





}